public with sharing class MonthlyCallPlanOverride{
    public MonthlyCallPlan__c mcp{
        get{
            if(mcp == null){
                mcp = new MonthlyCallPlan__c();
            }
            return mcp; 
        }
        set;
    }
    public String msg{get;set;}
    public MonthlyCallPlanOverride(ApexPages.StandardController controller) {
        this.controller = controller;
    }
    private final ApexPages.StandardController controller;  
    
    public PageReference Save()
    {
     try{
        List<User> u = [Select Id, Name From User Where Id  =: UserInfo.getUserId()];
        String month_s  = mcp.PlanMonth__c;
        String year_s  = mcp.PlanYear__c;
        if((month_s == null)||(year_s == null)){
            msg = '您的年份或月份未填写！';
            return null;
        }
        if(u.size()>0){
            mcp.Name = u.get(0).Name + year_s + '年' + month_s + '拜访计划';
        }
        
        List<MonthlyCallPlan__c> haveRecord = [Select Id,Name From MonthlyCallPlan__c Where PlanMonth__c =: mcp.PlanMonth__c and PlanYear__c =: mcp.PlanYear__c and OwnerId  =: UserInfo.getUserId() ];
        if(haveRecord.size()>0){
            msg = '该计划已存在';
            return null;
        }
        else{
            msg = null;
            if((mcp.PlanMonth__c == null)||(mcp.PlanYear__c == null)){
                pageReference pr = new pageReference('/'+ mcp.Id);    
                pr.setredirect(true);
                return pr;            
            }
            insert mcp;
        }
        pageReference pr = new pageReference('/'+ mcp.Id);    
        pr.setredirect(true);
        return pr;       
        }
     catch (DmlException e) {
        ApexPages.addMessages(e);
        return null;
     }

    }
    static testMethod void MonthlyCallPlanOverrideTest()
    {
        Profile p  = [select id from profile where name = 'System Administrator' or name =: '系统管理员'];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', 
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='standarduser@testorg1.com');
        insert u1;
    
        MonthlyCallPlan__c add = new MonthlyCallPlan__c();
        add.OwnerId  = u1.Id;
        add.name = '拜访';
        add.PlanYear__c = '2010';
        add.PlanMonth__c = '12月';
        
        insert add;
              
        test.setCurrentPageReference(Page.eventdeletebuttonoverride);
        System.currentPageReference().getParameters().put('id', add.Id); 
    
    
        ApexPages.StandardController del = new ApexPages.StandardController(add);
        MonthlyCallPlanOverride testCase = new MonthlyCallPlanOverride(del);
        testCase.Save();
        testCase.mcp.PlanYear__c = '2010';
        testCase.mcp.PlanMonth__c = '12月';     
        testCase.Save();
       
    }

}